package com.hejx.security.service.impl;

import com.hejx.security.common.utils.ColUtil;
import com.hejx.security.dto.OnlineUser;
import com.hejx.security.manager.util.PasswordUtils;
import com.hejx.security.mapper.ResourceMapper;
import com.hejx.security.mapper.RoleMapper;
import com.hejx.security.mapper.UserMapper;
import com.hejx.security.pojo.Resource;
import com.hejx.security.pojo.Role;
import com.hejx.security.pojo.User;
import com.hejx.security.pojo.UserExample;
import com.hejx.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 追风少年
 *
 * @email doubihah@foxmail.com
 * @create 2017/12/27 13:54
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    public OnlineUser login(String username, String password) {
        password = PasswordUtils.EncryptPassword(password);
        User user = findUserByUsernameAndPassword(username, password);
        if(user == null){
            //TODO: 登录失败
            return null;
        }
        List<Role> roles = roleMapper.selectByUserId(user.getId());
        List<Resource> resources = null;
        if(!ColUtil.isEmpty(roles)){
            resources = resourceMapper.selectByRoles(roles);
        }
        OnlineUser onlineUser = new OnlineUser(user.getUsername()
                ,roles,resources);
        return onlineUser;
    }

    private User findUserByUsernameAndPassword(String username, String password){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        criteria.andPasswordEqualTo(password);
        List<User> users = userMapper.selectByExample(userExample);
        if(!ColUtil.isEmpty(users)){
            return users.get(0);
        }
        return null;
    }

}
